package com.momochen.demo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Created by momochen on 2017/3/17.
 */
public class NettyTcpServerBootstrap {
    private int port;// = 9877;//tcp 监听端口号

    public static void main(String[] args) throws IOException {
        new NettyTcpServerBootstrap();
    }

    public NettyTcpServerBootstrap() {
        this(12345);
    }

    public NettyTcpServerBootstrap(int port) {
        this.port = port;
        bind();
    }

    private void bind() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
//                    .childOption(ChannelOption.SO_RCVBUF, 1024 * 1024)
//                    .childOption(ChannelOption.SO_SNDBUF, 1024 * 1024)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new IdleStateHandler(60 * 10, 0, 60 * 10, TimeUnit.SECONDS)); // 读超时 写超时 所有超时 超时单位
                    //pipeline.addLast(new LoggingHandler(LogLevel.INFO)); // 日志
                    pipeline.addLast(new ByteArrayDecoder());
//                    pipeline.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
                    pipeline.addLast(new ByteArrayEncoder());
                    pipeline.addLast(new ServiceTcpHandler());
                }
            });

            //绑定端口，开始接收进来的连接
            // 我们继续，剩下的就是绑定端口然后启动服务。这里我们在机器上绑定了机器所有网卡上的 8080 端口。当然现在你可以多次调用 bind() 方法(基于不同绑定地址)。
            ChannelFuture future = bootstrap.bind(port).sync(); // (7)

            if (future.isSuccess()) {
                System.out.println("tcp server start---------------");
            }

            // 等待服务器  socket 关闭 。
            // 在这个例子中，这不会发生，但你可以优雅地关闭你的服务器。
            future.channel().closeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();

            System.out.println("tcp server close---------------");
        }
    }
}
